package com.ttloner.web;

import com.ttloner.pojo.User;
import com.ttloner.service.impl.UserService;
import com.ttloner.service.impl.UserServiceImp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistServlet extends HttpServlet {
    private UserService imp = new UserServiceImp();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
         * 功能逻辑：
         * 1.获取请求的参数
         * 2.检查验证码是否正确
         * 如果正确：
             * 3.检查用户名是否可用
             * 如果可用：保存到数据库，跳转到数据库
             * 如果不可用跳转到注册页面
         * 如果不正确：跳回到注册页面
         */
        //1.获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

        //2.检查验证码，由于现在还没完成自动生成验证码功能，故写死为abcde
        if("abcde".equalsIgnoreCase(code)){
            //3.检查用户名是否可用
            if(imp.existUsername(username)){
                System.out.println("用户名可用");
                int i = imp.registUser(new User(null, username, password, email));
                if(1==i){
                    System.out.println("注册成功");
                    request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request,response);
                }else {
                    request.setAttribute("wrongMSG","未知错误");
                    request.setAttribute("username",username);
                    request.setAttribute("password",password);
                    request.setAttribute("email",email);
                    request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
                }
            }else{
                //用户名已存在
                request.setAttribute("wrongMSG","用户名已存在");
                request.setAttribute("password",password);
                request.setAttribute("email",email);
                System.out.println("用户名已存在");
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }
        }else {
            System.out.println("验证码错误");
            request.setAttribute("wrongMSG","验证码错误");
            request.setAttribute("username",username);
            request.setAttribute("password",password);
            request.setAttribute("email",email);
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }

    }

}
